package com.travel.server.manager.impl.youzan;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.travel.common.exception.WorkCode;
import com.travel.common.exception.WorkException;
import com.youzan.open.sdk.client.auth.Token;
import com.youzan.open.sdk.client.core.DefaultYZClient;
import com.youzan.open.sdk.client.core.YZClient;
import com.youzan.open.sdk.client.oauth.model.OAuthToken;
import com.youzan.open.sdk.gen.v3_0_0.api.*;
import com.youzan.open.sdk.gen.v3_0_0.model.*;
import com.youzan.open.sdk.gen.v4_0_0.api.YouzanTradeGet;
import com.youzan.open.sdk.gen.v4_0_0.api.YouzanTradesSoldGet;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetParams;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradeGetResult;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetParams;
import com.youzan.open.sdk.gen.v4_0_0.model.YouzanTradesSoldGetResult;
import com.youzan.open.sdk.model.ByteWrapper;
import com.youzan.open.sdk.util.http.DefaultHttpClient;
import com.youzan.open.sdk.util.http.HttpClient;
import com.youzan.open.sdk.util.json.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.entity.ContentType;

import java.util.Date;

/**
 * @Author: LiZhenhui
 * @Date: 2018/11/26 16:14
 * @Desc:
 */
@Slf4j
public class YouzanSal {

    public static void refreshToken(){
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpClient.Params params = HttpClient.Params.custom()
                    .add("client_id", YouzanConfig.CLIENT_ID)
                    .add("client_secret", YouzanConfig.CLIENT_SECRET)
                    .add("grant_type", "silent")
                    .add("kdt_id", YouzanConfig.KDT_ID)
                    .setContentType(ContentType.APPLICATION_FORM_URLENCODED).build();
            String resp = httpClient.post("https://open.youzan.com/oauth/token", params);
            log.info("刷新有赞Token返回， {}", resp);
            if (StringUtils.isBlank(resp) || !resp.contains("access_token")) {
                throw new RuntimeException(resp);
            }
            OAuthToken token = JsonUtils.toBean(resp, new TypeReference<OAuthToken>() {
            });
            YouzanConfig.ACCESS_TOKEN = token.getAccessToken();
        }catch (Exception e){
            log.error("刷新有赞token异常：", e);
        }
    }

    public static YouzanTradesSoldGetResult queryOrderList(String status, Date startDate, Date endDate, Long pageNo, Long pageSize){
        try {
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanTradesSoldGetParams youzanTradesSoldGetParams = new YouzanTradesSoldGetParams();

            youzanTradesSoldGetParams.setPageNo(pageNo);
            youzanTradesSoldGetParams.setPageSize(pageSize);
            youzanTradesSoldGetParams.setStartCreated(startDate);
            youzanTradesSoldGetParams.setEndCreated(endDate);
            youzanTradesSoldGetParams.setStatus(status);

            YouzanTradesSoldGet youzanTradesSoldGet = new YouzanTradesSoldGet();
            youzanTradesSoldGet.setAPIParams(youzanTradesSoldGetParams);
            log.info("查询有赞订单列表请求, {}", JSONObject.toJSONString(youzanTradesSoldGetParams));
            YouzanTradesSoldGetResult result = client.invoke(youzanTradesSoldGet);
            log.info("查询有赞订单列表返回, {}", JSONObject.toJSONString(result));
            return result;
        }catch (Exception e){
            log.error("查询有赞订单列表异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static YouzanItemsCustomGetResult queryItem(String itemNo){
        try{
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanItemsCustomGetParams youzanItemsCustomGetParams = new YouzanItemsCustomGetParams();

            youzanItemsCustomGetParams.setItemNo(itemNo);

            YouzanItemsCustomGet youzanItemsCustomGet = new YouzanItemsCustomGet();
            log.info("查询有赞商品请求, {}", JSONObject.toJSONString(youzanItemsCustomGet));
            youzanItemsCustomGet.setAPIParams(youzanItemsCustomGetParams);
            YouzanItemsCustomGetResult result = client.invoke(youzanItemsCustomGet);
            log.info("查询有赞商品返回, {}", JSONObject.toJSONString(result));
            return result;
        }catch (Exception e){
            log.error("查询有赞商品异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static void updateYouzanItem(YouzanItemUpdateParams youzanItemUpdateParams){
        try{
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanItemUpdate youzanItemUpdate = new YouzanItemUpdate();
            youzanItemUpdate.setAPIParams(youzanItemUpdateParams);
            log.info("更新有赞商品请求, {}", JSONObject.toJSONString(youzanItemUpdate));
            YouzanItemUpdateResult result = client.invoke(youzanItemUpdate);
            log.info("更新有赞商品返回, {}", JSONObject.toJSONString(result));
        }catch (Exception e){
            log.error("更新有赞商品异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static YouzanItemcategoriesTagsGetResult queryTags(){
        try{
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanItemcategoriesTagsGetParams youzanItemcategoriesTagsGetParams = new YouzanItemcategoriesTagsGetParams();;
            YouzanItemcategoriesTagsGet youzanItemcategoriesTagsGet = new YouzanItemcategoriesTagsGet();
            youzanItemcategoriesTagsGet.setAPIParams(youzanItemcategoriesTagsGetParams);
            log.info("查询有赞分组请求, {}", JSONObject.toJSONString(youzanItemcategoriesTagsGet));
            YouzanItemcategoriesTagsGetResult result = client.invoke(youzanItemcategoriesTagsGet);
            log.info("查询有赞分组返回, {}", JSONObject.toJSONString(result));
            return result;
        }catch (Exception e){
            log.error("查询有赞商品分组异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static Long uploadImage(String fileUrl){
        try{
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanMaterialsStoragePlatformImgUploadParams youzanMaterialsStoragePlatformImgUploadParams = new YouzanMaterialsStoragePlatformImgUploadParams();

            ByteWrapper byteWrapper = new ByteWrapper(fileUrl);

            youzanMaterialsStoragePlatformImgUploadParams.setImage(new ByteWrapper[]{byteWrapper});

            YouzanMaterialsStoragePlatformImgUpload youzanMaterialsStoragePlatformImgUpload = new YouzanMaterialsStoragePlatformImgUpload();
            youzanMaterialsStoragePlatformImgUpload.setAPIParams(youzanMaterialsStoragePlatformImgUploadParams);
            YouzanMaterialsStoragePlatformImgUploadResult result = client.invoke(youzanMaterialsStoragePlatformImgUpload);
            log.info("上传有赞图片返回, {}", JSONObject.toJSONString(result));
            return result.getImageId();
        }catch (Exception e){
            log.error("上传有赞图片异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static YouzanTradeGetResult queryOrder(String tid){
        try {
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanTradeGetParams youzanTradeGetParams = new YouzanTradeGetParams();

            youzanTradeGetParams.setTid(tid);

            YouzanTradeGet youzanTradeGet = new YouzanTradeGet();
            youzanTradeGet.setAPIParams(youzanTradeGetParams);
            log.info("查询有赞订单请求 {}", JSONObject.toJSONString(youzanTradeGet));
            YouzanTradeGetResult result = client.invoke(youzanTradeGet);
            log.info("查询有赞订单返回 {}", JSONObject.toJSONString(result));
            return result;
        }catch (Exception e){
            log.error("查询有赞订单异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static YouzanItemGetResult queryItem(Long itemId){
        try {
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanItemGetParams youzanItemGetParams = new YouzanItemGetParams();

            youzanItemGetParams.setItemId(itemId);

            YouzanItemGet youzanItemGet = new YouzanItemGet();
            youzanItemGet.setAPIParams(youzanItemGetParams);
            log.info("查询有赞商品请求 {}", JSONObject.toJSONString(youzanItemGet));
            YouzanItemGetResult result = client.invoke(youzanItemGet);
            log.info("查询有赞商品返回 {}", JSONObject.toJSONString(result));
            return result;
        }catch (Exception e){
            log.error("查询有赞商品异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static YouzanUsersWeixinFollowerGetResult queryUser(Long fansId){
        try{
            YZClient client = new DefaultYZClient(new Token(YouzanConfig.ACCESS_TOKEN));
            YouzanUsersWeixinFollowerGetParams youzanUsersWeixinFollowerGetParams = new YouzanUsersWeixinFollowerGetParams();

            youzanUsersWeixinFollowerGetParams.setFansId(fansId);

            YouzanUsersWeixinFollowerGet youzanUsersWeixinFollowerGet = new YouzanUsersWeixinFollowerGet();
            youzanUsersWeixinFollowerGet.setAPIParams(youzanUsersWeixinFollowerGetParams);
            log.info("查询有赞用户请求 {}", JSONObject.toJSONString(youzanUsersWeixinFollowerGetParams));
            YouzanUsersWeixinFollowerGetResult result = client.invoke(youzanUsersWeixinFollowerGet);
            log.info("查询有赞用户返回 {}", JSONObject.toJSONString(result));
            return result;
        }catch (Exception e){
            log.info("查询有赞用户信息异常：", e);
            WorkCode workCode = WorkCode.OTHER_SYSTEM;
            workCode.setMessage("有赞API异常");
            throw new WorkException(workCode);
        }
    }

    public static void main(String[] args) throws Exception{
        System.out.println(JSONObject.toJSONString(queryUser(5820047860L)));
//        YouzanTradeGetResult result = queryOrder("E20181213171402037200001");
    }
}
